#include "serial.hpp"
#include <string>
serial::serial() {
  if (wiringPiSetup() < 0) {
    std::cout << "Setup Failed!\n";
  }
  if ((MySerial = serialOpen("/dev/ttyAMA1", 115200)) < 0) {
    std::cout << "Serial Failed!\n";
  }
}
serial::~serial() { serialClose(MySerial); }
void serial::send(std::string msg) {
  serialPrintf(MySerial, msg.c_str());
  delay(1000);
}

bool serial::receive(char &ch) {
  if (serialDataAvail(MySerial) > 0) {
    ch = serialGetchar(MySerial);
    std::cout << ch << std::endl;
    if (1) {
      ch=-1;
      return true;
    }
  }
  return false;
}
void serial::uart(std::string msg) {
  bool is_get = false;
  char ch;
  send(msg);
  std::cout << "发送消息: " << msg << std::endl;
  while (!is_get) {
    if (receive(ch)) {
      is_get = true;
    } else {
      is_get = false;
    }
  }
}

void serial::wait_receive(char &ch) {
  bool is_receive = false;
  while (!is_receive) {
    if (serialDataAvail(MySerial) > 0) {
      ch = serialGetchar(MySerial);
      if (ch == 'Y' || ch == 'y') {
        ch = -1; // 重置ch为-1
        is_receive = true;
      }
      std::cout << ch << std::endl;
    }
  }
}